<template>
  <div class="p-4">
    <el-card class="box-card">
      <div slot="header" class="clearfix flex justify-between">
        <el-form class="flex-grow" inline>
          <el-form-item>
            <el-button
                icon="el-icon-plus"
                type="success"
                @click="deBounceWrap(handleAdd)"
            >新增
            </el-button
            >
            <el-button
                icon="el-icon-delete"
                type="danger"
                @click="deBounceWrap(handleDelAll)"
            >批量删除
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <el-table
          :data="data"
          :default-expand-all="false"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          row-key="id"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" prop="id" width="150px"></el-table-column>
        <el-table-column label="分类名称" prop="title"></el-table-column>
        <el-table-column label="分类状态" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="APP展示" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.extra_id" type="success">{{ scope.row.extra_title }}</el-tag>
          </template>
        </el-table-column>


        <el-table-column
            label="背景图片（关联说明背景表）"
            prop="gift_desc_bg_url"
        >
          <template slot-scope="{ row }">
            <el-popover max-width="420" placement="right" trigger="hover">
              <img
                  :src="row.gift_desc_img_url"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
              />
              <img
                  slot="reference"
                  :src="row.gift_desc_img_url"
                  alt=""
                  style="width: 50px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="分类排序" prop="sort"></el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="deBounceWrap(handleEdit, scope.row)"
            >编辑
            </el-button
            >
            <!--  <el-button type="warning" plain size="mini" icon="el-icon-edit"
              >详情</el-button
            >
            <el-dropdown trigger="click" style="margin-left: 20px">
              <el-button type="primary"
                >操作<i class="el-icon-arrow-down el-icon--right"></i
              ></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>下架</el-dropdown-item>
                 <el-dropdown-item>定时任务</el-dropdown-item>
                  <el-dropdown-item>置顶</el-dropdown-item>
               <el-dropdown-item
                  @click.native="deBounceWrap(handleDel, scope.row)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
        :before-close="handleClose"
        :close-on-click-modal="false"
        :title="titleOptions[title]"
        :visible.sync="dialogVisible"
        width="40%"
        @close="handleClear"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <!-- <el-form-item prop="parent_category_id" label="父分类id">
          <el-cascader
            class="cascader"
            :change-on-select="true"
            v-model="selectedOptions"
            :options="options"
            :props="defaultParams"
            clearable
            @change="handleCascader"
          ></el-cascader>
        </el-form-item> -->
        <el-form-item label="分类名称" prop="category_name">
          <el-input
              v-model="form.category_name"
              clearable
              placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number
              v-model="form.sort"
              clearable
              placeholder="请输入排序"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="礼物说明背景id" prop="gift_desc_bg_id">
          <el-select
              v-model="form.gift_desc_bg_id"
              clearable
              placeholder="请选择礼物说明背景id"
          >
            <el-option
                v-for="item in descriptionList"
                :key="item.id"
                :value="item.id"
                clearable
                @click.native="handleOption(item)"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="APP展示" prop="extra_id">
          <el-select
              v-model="form.extra_id"
              clearable
              placeholder="请选择APP展示"
          >
            <el-option
                v-for="item in extraList"
                :key="item.id"
                :value="item.id"
                :label="item.title"
                clearable
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
            v-if="form.gift_desc_bg_id"
            label="背景图片"
            prop="picture"
        >
          <div class="avatar-uploader">
            <img :src="img_url" class="avatar"/>
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model="form.status" :label="1">启用</el-radio>
          <el-radio v-model="form.status" :label="0">禁用</el-radio>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button plain type="primary" @click="handleClose">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit, 'form')"
        >提交
        </el-button
        >
      </div>
    </el-dialog>

    <!-- 删除弹框 -->
    <!-- <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px"
    >
      <span style=""
        ><em style="font-style: normal; color: red">删除后不可恢复</em
        >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
import { IMG_UPLOAD_URL } from "@/data/basic_data";
import { getToken } from "@/utils/auth";

;
import {
  getListApi,
  addGiftList,
  editGiftList,
  delGiftList,
  giftAllBg,
  categoryExtra
} from "@/api/roomGift/giftClassification";

export default {
  data() {
    return {

      data: [],
      titleOptions: {
        add: "新增",
        edit: "编辑"
      },
      title: "add",
      rowData: {},
      form: {
        parent_category_id: 0,
        category_name: undefined,
        gift_desc_bg_id: undefined,
        sort: undefined,
        status: undefined,
        extra_id: undefined
      },
      img_url: "",
      rules: {
        category_name: [
          { required: true, message: "请输入分类名称", trigger: "change" }
        ],
        gift_desc_bg_id: [
          { required: true, message: "请选择礼物说明背景id", trigger: "change" }
        ],
        sort: [{ required: true, message: "请输入排序号", trigger: "blur" }],
        status: [
          { required: true, message: "请选择开启状态", trigger: "change" }
        ]
      },
      options: [],
      selectedOptions: [],
      defaultParams: {
        label: "title",
        value: "id",
        children: "children"
      },
      descriptionList: [], // 获取所有说明背景的接口
      dialogVisible: false,
      //删除
      deleteDialogVisible: false,
      //勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: "",
      extraList: [
        {
          id: 0,
          title: '全部'
        }
      ]
    };
  },
  created() {
    this.getList();
    this.getGiftBg();
    this.getCategoryExtra()
  },
  methods: {
    //列表
    getList() {
      getListApi().then(res => {
        this.data = res.data;
        this.options = this.getTreeData(res.data);
      });
    },
    //递归
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 获取展示分类
    getCategoryExtra () {
      categoryExtra().then(res => {
        if(res.code === 200) {
          this.extraList.push(...res.data)
        }
      })
    },
    handleCascader(value) {

      this.form.parent_category_id = this.selectedOptions[
      this.selectedOptions.length - 1
          ];

    },
    //获取所有礼物背景
    getGiftBg() {
      giftAllBg().then(res => {
        this.descriptionList = res.data;
      });
    },
    handleOption(value) {

      this.form.gift_desc_bg_id = value.id;
      this.img_url = value.img_url;
    },
    //新增
    handleAdd() {
      this.title = "add";
      this.dialogVisible = true;
    },

    // 编辑
    handleEdit(row) {
      this.title = "edit";
      this.rowData = row;
      console.log(row)
      this.form.parent_category_id = this.rowData.parent_id;
      if (this.rowData.parent_id) {
        this.selectedOptions = this.rowData.parent_id;
      }
      this.form.category_name = this.rowData.title;
      this.form.gift_desc_bg_id = this.rowData.gift_desc_bg_id;
      this.img_url = this.rowData.gift_desc_img_url;
      this.form.status = this.rowData.status;
      this.form.sort = this.rowData.sort;
      this.form.extra_id = this.rowData.extra_id
      this.dialogVisible = true;
    },
    handleSumbit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "add") {
            if (!this.form.parent_category_id) {
              this.form.parent_category_id = 0;
            }
            let data = {
              parent_category_id: this.form.parent_category_id,
              category_name: this.form.category_name,
              gift_desc_bg_id: this.form.gift_desc_bg_id,
              sort: this.form.sort,
              status: this.form.status,
              extra_id: this.form.extra_id
            };

            addGiftList(data).then(res => {
              if (res.code === 200) {
                this.$message.success("提交成功");
                this.getList();
                this.dialogVisible = false;
              } else {
              }
            });
          }
          if (this.title === "edit") {
            let data1 = {
              id: this.rowData.id,
              parent_category_id: this.form.parent_category_id,
              category_name: this.form.category_name,
              gift_desc_bg_id: this.form.gift_desc_bg_id,
              sort: this.form.sort,
              status: this.form.status,
              extra_id: this.form.extra_id
            };

            editGiftList(data1).then(res => {
              if (res.code === 200) {
                this.$message.success("编辑成功");
                this.getList();
                this.dialogVisible = false;
              }
            });
          }
        } else {

          return false;
        }
      });
    },
    //清空表单
    handleClose() {
      this.dialogVisible = false;
    },
    handleClear() {
      this.$refs["form"].resetFields();
      this.form = {
        parent_category_id: undefined,
        category_name: undefined,
        gift_desc_bg_id: undefined,
        sort: undefined,
        status: undefined,
        extra_id: undefined
      };
      this.selectedOptions = [];
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelAll() {
      if (this.multipleSelection.length) {
        /* 存在勾选数据 */
        const ids = this.multipleSelection.reduce(
            (pre, currRow) => {
              pre += `${currRow.id},`;
              return pre;
            },
            ""
        );
        this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
            .then(() => {
              delGiftList({ ids })
                  .then(() => this.$message.success("删除成功！"))
                  .catch(console.error)
                  .finally(() => /* 刷新数据 */ {
                    this.multipleSelection = [];
                    this.getList();
                  });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除"
              });
            });
      } /* 不存在勾选数据 */ else {
        this.$message.warning("请勾选要删除的数据！");
      }
    }
    // 删除
    // handleDel(row) {
    //   this.dataIds = { ids: `${row.id}` };
    //   this.deleteDialogVisible = true;
    // },
    // 确定删除
    // confirmDelete() {
    //   delGiftList(this.dataIds).then((response) => {
    //     if (response.code === 200) {
    //       this.getList();
    //       this.deleteDialogVisible = false;
    //       this.$notify({
    //         type: "success",
    //         message: "操作成功",
    //       });
    //     }
    //   });
    // },
  }
};
</script>
<style lang="scss" scoped>
::v-deep.avatar-uploader {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
  width         : 100px;
}
</style>
